<template>
  <div>
    <breadNav></breadNav>
    <el-card class="box-card">
      <el-alert title="注意：只允许为三级分类设置相关参数！" type="warning" :closable="false" show-icon>
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span style="float:left">选择商品分类</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader v-model="selectedKeys" :options="cateList" :props="cascaderProps" style="width:500px"
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isdisabled" size="mini" style="float: left" @click="addDialog = true">
            添加参数
          </el-button>
          <!-- 动态参数表格-->
          <el-table :data="manyParams">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 设置closable属性可以定义一个标签是否可移除。 -->
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(scope.row, i)">{{
                    item
                }}
                </el-tag>
                <el-input style="width: 200px" class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="inputTagRef" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <!-- 操作列 -->
            <el-table-column>
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isdisabled" size="mini" style="float: left" @click="addDialog = true">
            添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyParams">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 设置closable属性可以定义一个标签是否可移除。 -->
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(scope.row, i)">{{
                    item
                }}
                </el-tag>
                <el-input style="width: 200px" class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="inputTagRef" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <!-- 操作列 -->
            <el-table-column>
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态参数/静态属性对话框 -->
      <el-dialog :title="'添加' + titleText" :visible.sync="addDialog" width="30%">
        <!-- 添加参数的表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑动态参数/静态属性对话框 -->
      <el-dialog :title="'修改' + titleText" :visible.sync="editDialog" width="30%">
        <!-- 修改参数的表单 -->
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="addEditParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import breadNav from '../breadNav.vue'
export default {
  components: {
    breadNav
  },
  data() {
    return {
      // 分类列表数据
      cateList: [],
      // 级联选择器双向绑定到的数组对象
      selectedKeys: [],
      // 级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
      },
      // Tab栏激活的对象
      activeName: 'many',
      // 分类参数列表
      // paramsList: [],
      // 动态参数数据
      manyParams: [],
      // 静态参数数据
      onlyParams: [],
      // 添加参数对话框
      addDialog: false,
      // 添加表单数据
      addForm: {
        attr_name: ''
      },
      // 添加表单规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 修改表单的数据对象
      editForm: {

      },
      // 编辑参数对话框
      editDialog: false,
      // // 输入框input展示与否
      // inputVisible: false,
      // // 输入框的值
      // inputValue: '',


    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error("获取商品列表失败");
      this.cateList = res.data;
    },
    // 级联选择器选择时触发的事件
    handleChange() {
      // console.log(this.selectedKeys);
      // 控制只能选择第三级分类
      if (this.selectedKeys.length !== 3) return this.selectedKeys = [];
      this.cateList.cat_id = this.selectedKeys[2];
      this.getParamsList();

    },
    // Tab栏切换
    handleTabClick() {
      // console.log(this.activeName);
      this.getParamsList();
    },
    // 获取分类参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(`categories/${this.cateList.cat_id}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$msg("获取分类参数列表失败");
      // this.paramsList = res.data;
      // forEach循环遍历,以逗号分隔，将字符串转化为数组
      res.data.forEach(item => {
        // 判断的目的：避免空字符串也被渲染成标签
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
        // 添加每项属性
        // this.$set(item, "inputVisible", false)
        // this.$set(item, "inputValue", '')
        item.inputVisible = false;
        item.inputValue = '';
      })
      // console.log(res);

      // 动态参数数据
      if (this.activeName === "many") {
        this.manyParams = res.data;
      } else {
        // 静态参数数据
        this.onlyParams = res.data;
      }
      // console.log(this.manyParams)

    },
    // 发起请求添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateList.cat_id}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$msg.error("添加失败");
        this.$msg.success("添加成功")
        this.getParamsList();
      })
      this.addDialog = false;
    },
    // 根据id查询参数,并显示对话框
    async showEditDialog(id) {
      this.editDialog = true;
      const { data: res } = await this.$http.get(`categories/${this.cateList.cat_id}/attributes/${id}`, { attr_sel: this.activeName })
      // console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("获取参数失败");
      this.editForm = res.data;
    },
    // 编辑提交参数
    addEditParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(`categories/${this.cateList.cat_id}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        // console.log(res);
        if (res.meta.status !== 200) return this.$msg.error("编辑参数失败");
        this.getParamsList();
        this.editDialog = false;
      })
    },
    // 删除参数
    async removeParams(id) {
      const { data: res } = await this.$http.delete(`categories/${this.cateList.cat_id}/attributes/${id}`)
      // console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("删除参数失败");
      this.$msg.success("删除参数成功")
      this.getParamsList();
      this.editDialog = false;
    },
    // 重置对话框

    // 编辑提交参数可选项，保存在数据库中
    async setAttr_vals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateList.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // attr_vals属性值是字符串
        attr_vals: row.attr_vals.join(',')
      });
      console.log(res);
      if (res.meta.status !== 200) return this.$msg.error("添加参数失败");
    },
    // 添加参数可选项
    handleInputConfirm(row) {
      console.log(row.inputValue)
      // 输入内容为空时
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = '';
        return;
      }
      // 输入内容不为空
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;
      // 发起请求，编辑提交参数可选项，保存在数据库中
      this.setAttr_vals(row);
    },
    // 删除参数可选项
    handleClose(row, i) {
      // splice删除数组中的数据
      console.log(row)
      row.attr_vals.splice(i, 1);
      this.setAttr_vals(row);

    },
    // 展示输入框
    showInput(row) {
      // console.log(row)
      row.inputVisible = true;
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.inputTagRef.$refs.input.focus();
      });
    },
  },
  // 计算属性
  computed: {
    // 添加动态参数/静态属性按钮的禁用状态
    isdisabled() {
      return this.selectedKeys.length !== 3 ? true : false;
    },
    // 对话框标题
    titleText() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    },
  },
  created() {
    this.getCateList();
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag {
  margin: 10px;
}
</style>